package Proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;

import org.apache.commons.beanutils.ConvertUtilsBean;

public final class PropertyConverter<T> extends ConvertUtilsBean {
	private final Class<T> targetType;

	private PropertyConverter(Class<T> targetType) {
		this.targetType = targetType;
	}

	public static <T> PropertyConverter<T> to(Class<T> targetType) {
		return new PropertyConverter<T>(targetType);
	}

	@SuppressWarnings("unchecked")
	public T from(final Map<String, String> map) {
		return (T) Proxy.newProxyInstance(targetType.getClassLoader(),
				new Class[] { targetType }, new InvocationHandler() {
					public Object invoke(Object proxy, Method method,Object[] args) {
						String value = map.get(method.getName());
						if (value == null) {
							Object defaultValue = method.getDefaultValue();
							if (defaultValue == null) {
								System.out.println("PropertyConverter error ..");
							}
							return defaultValue;
						}
						return convert(value, method.getReturnType());
					}
				});
	}
}
